/**
 * 
 */
package com.ckex.learn.lucene.index;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

import com.ckex.learn.lucene.domain.TradeDo;

/**
 * @author ckex created 2014-1-16 上午10:26:43
 * @explain -
 */
public class IndexService {

    protected static Logger          logger    = Logger.getLogger(IndexService.class);

    //    private static String            CHARSET   = "UTF-8";

    /** 索引文件存储路径. */
    public static String             indexPath = "index/trade";

    //为true 时，智能切分，false 或无参时最细粒度切分
    private static Analyzer          analyzer  = new IKAnalyzer(Boolean.TRUE);

    private static File              indexFile = null;

    private static IndexWriterConfig iwc       = null;

    private static Directory         dir       = null;

    static {
        try {
            indexFile = new File(indexPath);
            if (!indexFile.exists()) {
                indexFile.mkdirs();
            }
            iwc = new IndexWriterConfig(Version.LUCENE_44, analyzer);
            dir = FSDirectory.open(indexFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param tradeDo : 被索引的对像
     * @param create : 是否创建新的索引文件
     * @return
     */
    public static boolean createIndexFile(TradeDo tradeDo, boolean create) {

        if (tradeDo == null) {
            return Boolean.FALSE;
        }

        try {

            Long start = System.currentTimeMillis();

            //            logger.info("Indexing to directory '" + indexFile.getAbsolutePath() + "'...");

            if (create) {
                // 在目录中创建一个新的索引,删除任何先前索引文件:
                iwc.setOpenMode(OpenMode.CREATE);
            } else {
                // 新文档添加到一个现有的索引:
                iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
            }
            long t1 = System.currentTimeMillis() - start;
            IndexWriter writer = new IndexWriter(dir, iwc);

            writerIndex(writer, tradeDo);

            writer.close();

            logger.info(String.format("{--加截时间: (%s)---- 创建索引时间: (%s)---- 总耗时: (%s) . }", t1,
                    (System.currentTimeMillis() - start - t1), (System.currentTimeMillis() - start)));

        } catch (IOException e) {
            e.printStackTrace();
        }

        return Boolean.TRUE;
    }

    private static void writerIndex(IndexWriter writer, TradeDo tradeDo) throws IOException {

        Document doc = new Document();

        Field idField = new LongField("id", tradeDo.getId(), Field.Store.YES);
        doc.add(idField);

        Field buyerIdField = new LongField("buyer_id", tradeDo.getBuyerId(), Field.Store.YES);
        doc.add(buyerIdField);

        Field nickField = new StringField("nick", tradeDo.getBuyerNick(), Field.Store.YES);
        doc.add(nickField);

        Field receiverNameField = new StringField("receiver_name", tradeDo.getReceiverName(),
                Field.Store.NO);
        doc.add(receiverNameField);

        Field receiverCityField = new StringField("receiver_city", tradeDo.getReceiverCity(),
                Field.Store.NO);
        doc.add(receiverCityField);

        if (writer.getConfig().getOpenMode() == OpenMode.CREATE) {
            // New index, so we just add the document (no old document can be there):
            writer.addDocument(doc);
        } else {
            // Existing index (an old copy of this document may have been indexed) so 
            // we use updateDocument instead to replace the old one matching the exact 
            // path, if present:
            //            writer.updateDocument(new Term("path", file.getPath()), doc);
            Term term = new Term("id", tradeDo.getId().toString());
            writer.updateDocument(term, doc);
        }

        writer.commit();

    }
}
